<template>
    <div class="pop-container">
        <el-dialog :modal-append-to-body="false" v-model="visibleDialog" width="400px" :title="title"
            :close-on-click-modal="false" :close-on-press-escape="false" @close="close">
            <el-form :model="formData" ref="formRef" :rules="formRules" label-position="top" label-width="120px"
                @submit.prevent>
                <el-form-item label="会话名称" prop="name">
                    <el-input v-model="formData.name" :maxlength="50"  placeholder="请输入会话名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="close">取 消</el-button>
                    <el-button @click.prevent="save" type="primary" :loading="loading">
                        <span v-if="!loading">保存</span>
                        <span v-else>保存中...</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { conversationName } from '@/api/chat'
const { proxy } = getCurrentInstance()
const visibleDialog = ref(false)
const title = ref('重命名会话')
const loading = ref(false)

const initData = {
    id: '',
    name: '',
}

const formData = ref({})
const formRules = ref({
    name: [
        { required: true, message: "会话名称不能为空", trigger: "blur" },
    ],
})
const emit = defineEmits(['success'])
// 设置数据
const setFormData = async (data) => {
    for (const key in formData.value) {
        if (data[key] != null && data[key] != undefined) {
            formData.value[key] = data[key];
        }
    }
};
const open = (type) => {
    formData.value = { ...initData }
    visibleDialog.value = true
}
const close = () => {
    visibleDialog.value = false;
    loading.value = false;
}
const save = () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            loading.value = true;
            if (formData.value.id && formData.value.name) {
                conversationName(formData.value.id, {
                    name: formData.value.name
                }).then(response => {
                    close();
                    emit('success', response);
                    proxy.$modal.msgSuccess("重命名成功");
                }).catch(error => {
                    loading.value = false;
                });
            }
        }
    });
}

defineExpose({ open, setFormData });
</script>

<style lang="scss" scoped></style>